import express from 'express';
import mongolass from './db/mongolass.js';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import connectMongo from 'connect-mongo';
import config from 'config-lite';
import history from 'connect-history-api-fallback';
import chalk from 'chalk';
import log4js from 'log4js';
import useLog from './log'

const app = express();
const MongoStore  = connectMongo(session);

var log = log4js.getLogger("app");
/*
* "*" 匹配所有请求进行 请求头，跨域设置。
* app.all 是完整匹配，use 只匹配前缀
* 访问 /a use 和 all 都会被调用；访问 /a/b 只有 use 被调用
* */
app.all('*', (req, res, next) => {
    res.header("Access-Control-Allow-Origin", req.headers.Origin || req.headers.origin || 'https://cangdu.org');
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Access-Control-Allow-Credentials", true); //可以带cookies
    res.header("X-Powered-By", '3.2.1')
    if (req.method == 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
});

// log4j 日志 放在所有use前面
useLog(app)

app.use(cookieParser());

app.use(session({
    name: config.session.name,
    secret: config.session.secret,
    resave: true,
    saveUninitialized: false,
    cookie: config.session.cookie,
    store: new MongoStore({
        url: config.mongodb
    })
}));
router(app);
app.use(history());
app.use(express.static('./public'));

log.info("程序启动成功" + mongolass)

app.listen(config.port,() =>{
    console.log(
        chalk.green(`监听端口 ${config.port}`)
    )
});
